package com.definesys.smecrailtransit.module.MonthForm;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.SmecManager.SmecKpManager.SmecKpUtils;
import com.definesys.smecrailtransit.adapter.LineStationAdapter.LineStationAdapter;
import com.definesys.smecrailtransit.adapter.LineStationAdapter.LineStationFaultAdapter;
import com.definesys.smecrailtransit.api.SmecRailApi;
import com.definesys.smecrailtransit.api.SmecRailConstant;
import com.definesys.smecrailtransit.base.SmecBaseFragment;


import com.definesys.smecrailtransit.databinding.FragmentMonthFormBinding;
import com.definesys.smecrailtransit.adapter.SelctLineAdapter.SelectLineAdapter;
import com.definesys.smecrailtransit.adapter.SelectUserAdapter.SelectUserAdapter;
import com.definesys.smecrailtransit.module.MonthForm.ViewController.ViewController;
import com.definesys.smecrailtransit.module.MonthForm.bean.MonthFormBean;
import com.definesys.smecrailtransit.module.MonthForm.bean.StatisticBean;
import com.definesys.smecrailtransit.module.MonthForm.dialog.MonthFormDialog;
import com.definesys.smecrailtransit.utils.ToastyUtils;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;


import java.util.ArrayList;
import java.util.HashMap;

import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;

import static com.definesys.smecrailtransit.MainActivity.WAY_TO_FRAGMNET;


/**
 * Created by xupeizuo on 2017/7/20.
 */

public class MonthFormFragment extends SmecBaseFragment<MonthFormPresenter> {
    //RxJava,组件间通讯的静态常量
    public static final String CLOSE_DIALOG_BACKGROUND = "closeDialogBackground(Object o)";
    public static final String CHANGE_MONTH = "changeMonthMonthForm(Object o)";
    public static final String CHANGE_USER = "changeUserMonthForm(Object o)";
    public static final String CHANGE_LINE = "changeLineMonthForm(Object o)";
    public static final String GET_MONTH_FORM_ERROR = "getMonthFormError(Object o)";
    public static final String GET_MONTH_FORM_SUCCESS = "getMonthFormSuccess(Object o)";
    public static final String GET_DETAIL = "getDetailMF(Object o)";
    public static final String LOAD = "load(Object o)";
    public static final String JPUSH_LOAD_MONTH_FORM = "jpushLoadMonthForm(Object o)";
    public static final String SEND_EMAIL = "SEND_Email(Object o)";

    private FragmentMonthFormBinding fragmentMonthFormBinding;
    private MonthFormPresenter monthFormPresenter;

    private LineStationFaultAdapter lineStationAdapter1;
    private LineStationFaultAdapter lineStationAdapter2;
    private SelectUserAdapter selectUserAdapter;
    private SelectLineAdapter selectLineAdapter;
    private DisplayMetrics dm;
    private ViewController viewController;



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentMonthFormBinding= DataBindingUtil.inflate(inflater, R.layout.fragment_month_form,container,false);
        monthFormPresenter = getPersenter();
        viewController = new ViewController(fragmentMonthFormBinding,monthFormPresenter,mRxBus);
        dm = getResources().getDisplayMetrics();
        _initView();
        return fragmentMonthFormBinding.getRoot();
    }

    private void _initView(){
        //设置下拉刷新的属性
        fragmentMonthFormBinding.refreshLayout.setHeaderView(SmecRailConstant.getSinaRefreshView());
        fragmentMonthFormBinding.refreshLayout.setAutoLoadMore(true);
        fragmentMonthFormBinding.refreshLayout.setEnableOverScroll(false);
        fragmentMonthFormBinding.refreshLayout.setEnableLoadmore(false);
        fragmentMonthFormBinding.refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                viewController.getNetWorkData();
            }
        });

        //设置线路数据
        viewController.getLineList().add("12号线");
        viewController.getLineList().add("1号线");
        viewController.getLineList().add("2号线");
        viewController.getLineList().add("3号线");
        viewController.getLineList().add("4号线");
        viewController.getLineList().add("5号线");
        viewController.getLineList().add("9号线");
        viewController.getLineList().add("16号线");

        //设置界面显示的数据
        int l=viewController.getSelectLine()!=null ? viewController.getSelectLine().length()-2:0;
        fragmentMonthFormBinding.nowLine.setText(viewController.getSelectLine().substring(0,l));
        fragmentMonthFormBinding.nowUser.setText(viewController.getSelectUser());
        fragmentMonthFormBinding.startDate.setText(viewController.getStartDate());
        fragmentMonthFormBinding.endDate.setText(viewController.getEndDate());

        //设置界面的Adapter
        lineStationAdapter1 = new LineStationFaultAdapter(dm,this.mRxBus,SmecRailApi.MonthCode.MONTHFORM,getContext());
        lineStationAdapter2 = new LineStationFaultAdapter(dm,this.mRxBus,SmecRailApi.MonthCode.MONTHFORM,getContext());

        selectUserAdapter = new SelectUserAdapter(this.mRxBus, SmecRailApi.MonthCode.MONTHFORM);
        selectLineAdapter = new SelectLineAdapter(viewController.getLineList(),this.mRxBus,SmecRailApi.MonthCode.MONTHFORM);

        viewController.setSelectLineAdapter(selectLineAdapter);
        viewController.setSelectUserAdapter(selectUserAdapter);

        //选择运营商下拉框
        fragmentMonthFormBinding.selectUser.setLayoutManager(new LinearLayoutManager(getActivity()));
        fragmentMonthFormBinding.selectUser.setAdapter(selectUserAdapter);
        //选择线路下拉框
        fragmentMonthFormBinding.selectLine.setLayoutManager(new LinearLayoutManager(getActivity()));
        fragmentMonthFormBinding.selectLine.setAdapter(selectLineAdapter);

        //界面图标
        fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
        fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
        fragmentMonthFormBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);
    }


    public static MonthFormFragment newInstance() {
        Bundle args = new Bundle();
        MonthFormFragment fragment = new MonthFormFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected MonthFormPresenter getPersenter() {
        return new MonthFormPresenter(getActivity());
    }

    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(WAY_TO_FRAGMNET)
            }
    )
    public void intFragment(String position){
        if(position.equals("3")){
            fragmentMonthFormBinding.getRoot().postDelayed(new Runnable() {
                @Override
                public void run() {
                    fragmentMonthFormBinding.refreshLayout.startRefresh();
                }
            },200);
        }
    }


    /**
     * 当切换tab,离开页面时，关闭本页面中的dialog背景层
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(LOAD)
            }
    )
    public void load(Object o){
        this.viewController.getNetWorkData();
    }

    /**
     * 当从推送点击跳转到该页面时
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(JPUSH_LOAD_MONTH_FORM)
            }
    )
    public void jpushLoad(HashMap<String,String> hashMap){
        fragmentMonthFormBinding.calendar.clearSelection();
        if(hashMap.get("from") == null || hashMap.get("from").equals("") || hashMap.get("to") == null || hashMap.get("to").equals("")){
            //this.viewController.getNetWorkData();
        }else{
            this.viewController.setStartDate(hashMap.get("from"));
            this.viewController.setEndDate(hashMap.get("to"));
            this.viewController.getNetWorkData();
            fragmentMonthFormBinding.startDate.setText(hashMap.get("from"));
            fragmentMonthFormBinding.endDate.setText(hashMap.get("to"));
        }
    }


    /**
     * 当切换tab,离开页面时，关闭本页面中的dialog背景层
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CLOSE_DIALOG_BACKGROUND)
            }
    )
    public void closeDialogBackground(Object o){
        this.fragmentMonthFormBinding.choice.setVisibility(View.GONE);
        this.fragmentMonthFormBinding.pull.setVisibility(View.GONE);
        this.fragmentMonthFormBinding.line.setVisibility(View.GONE);
    }

    /**
     * 当切换运营商时
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CHANGE_USER)
            }
    )
    public void changeUser(Object o){
        this.fragmentMonthFormBinding.pull.setVisibility(View.GONE);
        this.fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);

        viewController.setSelectUser(String.valueOf(o));
        fragmentMonthFormBinding.nowUser.setText(viewController.getSelectUser());

        viewController.getNetWorkData();
    }

    /**
     * 当切换线路时
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CHANGE_LINE)
            }
    )
    public void changeLine(Object o){
        if((boolean)o){
            ToastyUtils.showWaringToast(this.fragmentMonthFormBinding.getRoot().getContext(),
                    "当前版本只有12号线的数据");
        }
        this.fragmentMonthFormBinding.line.setVisibility(View.GONE);
        this.fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);

    }

    /**
     * 获取页面数据成功
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_MONTH_FORM_SUCCESS)
            }
    )
    public void getMonthFormSuccess(MonthFormBean o){
        viewController.getLocalData(o);
        changeView();
        fragmentMonthFormBinding.refreshLayout.finishRefreshing();
    }

    /**
     * 获取页面数据失败
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_MONTH_FORM_ERROR)
            }
    )
    public void getMonthFormError(Object o){
        fragmentMonthFormBinding.refreshLayout.finishRefreshing();
    }


    /**
     * 获取站点详情
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_DETAIL)
            }
    )
    public void getDetail(HashMap<String,Object> o){
        if( (int)o.get("ftValue") != 0 || (int)o.get("value") != 0){
            MonthFormDialog monthFormDialog = new MonthFormDialog(getContext(),monthFormPresenter,R.style.project_back, (int)o.get("stationId"), viewController.getStartDate(),viewController.getEndDate(),viewController.getFaultType());
            monthFormDialog.setTitle((String)o.get("stationName"));
            monthFormDialog.show();
        }else{
            ToastyUtils.showWaringToast(fragmentMonthFormBinding.getRoot().getContext(),
                    o.get("stationName") + " " +"这段时间内没有电梯发生故障");
        }
    }

    /**
     * 发送邮件
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(SEND_EMAIL)
            }
    )
    public void sendEmail(HashMap<String,Object> o){
        SmecKpUtils.showWithStatus();
        monthFormPresenter.sendEmail(o);

    }

    //处理根据获取的数据，跟新页面
    private void changeView(){
        //设置运营商下拉列表
        if(viewController.getUserList() != null & viewController.getUserList().size() != 0){
            selectUserAdapter.setList(viewController.getUserList());
        }
        selectUserAdapter.notifyDataSetChanged();

        //设置站点显示数据
        if(lineStationAdapter1.getList() == null || lineStationAdapter1.getList().size() == 0){
            if(viewController.getList() != null & viewController.getList().size() != 0){
                lineStationAdapter1.setList(viewController.getList());
                lineStationAdapter1.showAnimation = true;
            }

            fragmentMonthFormBinding.invalidateAll();

            fragmentMonthFormBinding.getRoot().postDelayed(new Runnable() {
                @Override
                public void run() {
                    lineStationAdapter1.showAnimation = false;
                }
            },500);

            fragmentMonthFormBinding.recyclerView.setItemAnimator(new SlideInLeftAnimator());
            fragmentMonthFormBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            fragmentMonthFormBinding.recyclerView.setAdapter(lineStationAdapter1);

            lineStationAdapter2.setList(new ArrayList<>());
        }else{
            if(viewController.getList() != null & viewController.getList().size() != 0){
                lineStationAdapter2.setList(viewController.getList());
                lineStationAdapter2.showAnimation = true;
            }
            lineStationAdapter2.notifyDataSetChanged();

            fragmentMonthFormBinding.invalidateAll();

            fragmentMonthFormBinding.getRoot().postDelayed(new Runnable() {
                @Override
                public void run() {
                    lineStationAdapter2.showAnimation = false;
                }
            },500);

            fragmentMonthFormBinding.recyclerView.setItemAnimator(new SlideInLeftAnimator());
            fragmentMonthFormBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            fragmentMonthFormBinding.recyclerView.setAdapter(lineStationAdapter2);

            lineStationAdapter1.setList(new ArrayList<>());
        }

        //设置数量
        StatisticBean statisticBean = viewController.getElevatorNumber();
        fragmentMonthFormBinding.ftNumber.setText("自动扶梯：" + statisticBean.getFtCount() + "台");
        fragmentMonthFormBinding.sjtNumber.setText("升降梯：" + statisticBean.getSjtCount() + "台");
        fragmentMonthFormBinding.totalNumber.setText("总计：" + statisticBean.getTotalCount() + "台");

    }

}
